<template>
  <div>
    <header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
    </header>
    <main>
      <div class="title">
        <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
        <el-steps :space="200" :active="active" finish-status="success">
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <el-tabs
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息">
            <el-form
              :model="form"
              status-icon
              ref="ruleForm"
              class="demo-ruleForm"
              label-position="top"
            >
              <el-form-item
                label="商品名称"
                :rules="[
                  {
                    required: true,
                    message: '请输入商品名称',
                    trigger: 'blur',
                  },
                ]"
                prop="goods_name"
              >
                <el-input v-model="form.goods_name"></el-input>
              </el-form-item>
              <el-form-item
                label="商品价格"
                :rules="[
                  {
                    required: true,
                    message: '请输入商品价格',
                    trigger: 'blur',
                  },
                  {
                    type: 'number',
                    message: '价格必须为数字值',
                    trigger: ['blur', 'change'],
                    pattern: /^\d+$/,
                  },
                ]"
                prop="goods_price"
              >
                <el-input v-model.number="form.goods_price"></el-input>
              </el-form-item>
              <el-form-item
                label="商品重量"
                :rules="[
                  {
                    required: true,
                    message: '请输入商品重量',
                    trigger: 'blur',
                  },
                  {
                    message: '重量必须为数字值',
                    trigger: ['blur', 'change'],
                    pattern: /^\d+$/,
                  },
                ]"
                prop="goods_weight"
              >
                <el-input v-model.number="form.goods_weight"></el-input>
              </el-form-item>
              <el-form-item
                label="商品数量"
                :rules="[
                  {
                    required: true,
                    message: '请输入商品数量',
                    trigger: 'blur',
                  },
                  {
                    message: '数量必须为数字值',
                    trigger: ['blur', 'change'],
                    pattern: /^\d+$/,
                  },
                ]"
                prop="goods_number"
              >
                <el-input v-model.number="form.goods_number"></el-input>
              </el-form-item>
              <el-form-item
                label="商品分类"
                :rules="[
                  {
                    required: true,
                    message: '请选择商品分类',
                  },
                ]"
                prop="goods_cat"
              >
                <el-cascader
                  :value="value"
                  :options="options"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品参数">
            <el-form>
              <el-form-item
                :label="item.attr_name"
                v-for="(item, index) in list"
                :key="index"
              >
                <el-checkbox-group
                  v-model="checkedValues"
                  @change="checkedChange(index, item)"
                >
                  <el-checkbox
                    v-for="(item2, index) in item.attr_vals == ''
                      ? []
                      : item.attr_vals.split(',')"
                    :key="index"
                    :label="item2"
                    border
                  ></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品属性">
            <el-form v-if="list2.length">
              <el-form-item
                :label="item.attr_name"
                v-for="(item, index) in list2"
                :key="index"
              >
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品图片">
            <!-- action="http://vue-shop-api-t.itheima.net/api/private/v1/upload"
              :headers="{ Authorization: token }" -->
            <!-- :on-success="handleSuccess" -->
            <el-upload
              action="#"
              :http-request="uploadFile"
              class="upload-demo"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :before-upload="beforeAvatarUpload"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容">
            <quill-editor
              v-model="form.goods_introduce"
              style="height: 300px"
            ></quill-editor>
            <div>
              <el-button
                type="primary"
                style="margin-top: 50px"
                @click="addGoods"
                >添加商品</el-button
              >
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </main>
  </div>
</template>
<script>
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { getCategories, getGoodsAttribute, addGoods } from "@/api/goods";
import request from "@/utils/request";
export default {
  name: "ShopAdd",
  components: {
    quillEditor,
  },
  data() {
    return {
      token: localStorage.getItem("token"),
      content: "",
      checkedValues: [],
      value: [],
      options: [],
      active: 0,
      list: [],
      list2: [],
      form: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_introduce: "",
        goods_cat: "",
        pics: [],
        attrs: [],
      },
    };
  },
  created() {
    this.getOptions();
  },
  methods: {
    async uploadFile(e) {
      // console.log(e);
      const formData = new FormData();
      formData.append("file", e.file);
      // const res=await request({
      //   url:"http://vue-shop-api-t.itheima.net/api/private/v1/upload",
      //   method:"POST",
      //   data:formData
      // })
      // console.log(res)
      const xhr = new XMLHttpRequest();
      xhr.open(
        "post",
        "http://vue-shop-api-t.itheima.net/api/private/v1/upload"
      );
      //  xhr.responseType = 'json';
      // xhr.setRequestHeader("Content-Type", "form/data");
      // xhr.setRequestHeader("Content-Type", "application/json");
      xhr.setRequestHeader("Authorization", this.token);
      xhr.send(formData);
      xhr.addEventListener("loadend", () => {
        console.log(xhr.response);
        const response = JSON.parse(xhr.response);
        if (response.meta.status == 200) {
          this.form.pics.push({
            pic: response.data.tmp_path,
          });
        } else {
          this.$message.error(response.meta.msg);
        }
      });
    },
    // handleSuccess(response, file, fileList) {
    //   console.log(response);
    //   // this.form.pics.push(response.data.tmp_path);
    //   if (response.meta.status == 200) {
    //     this.form.pics.push({
    //       pic: response.data.tmp_path,
    //     });
    //   } else {
    //     this.$message.error(response.meta.msg);
    //   }
    // },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    checkedChange(index, item) {
      this.form.attrs[index] = {
        attr_vals: this.checkedValues.join(","),
        attr_id: item.attr_id,
      };
    },
    async tabClicked(tab) {
      // console.log(this.value);
      if (this.value.length == 0) {
        return;
      }
      const res = await getGoodsAttribute({
        id: this.value[this.value.length - 1],
        sel: tab.index == 1 ? "many" : "only",
      });
      console.log(res);
      if (tab.index == 1) {
        this.list = res.data.data;
        this.list.forEach((item) => {
          this.form.attrs.push({
            attr_vals: "",
            attr_id: item.attr_id,
          });
        });
        // console.log(this.form.attrs);
      } else if (tab.index == 2) {
        this.list2 = res.data.data;
      }
    },
    async addGoods() {
      // if (
      //   this.form.goods_name == "" ||
      //   this.form.goods_price == "" ||
      //   this.form.goods_weight == "" ||
      //   this.form.goods_number == "" ||
      //   this.form.goods_introduce == "" ||
      //   this.form.goods_cat == ""
      // ) {
      //   return this.$message({
      //     type: "error",
      //     message: "请填写完整信息",
      //   });
      // }
      if (this.form.goods_name == "") {
        return this.$message({
          type: "error",
          message: "请填写商品名称",
        });
      } else if (this.form.goods_price == "") {
        return this.$message({
          type: "error",
          message: "请填写商品价格",
        });
      } else if (this.form.goods_weight == "") {
        return this.$message({
          type: "error",
          message: "请填写商品重量",
        });
      } else if (this.form.goods_number == "") {
        return this.$message({
          type: "error",
          message: "请填写商品数量",
        });
      } else if (this.form.goods_introduce == "") {
        return this.$message({
          type: "error",
          message: "请填写商品简介",
        });
      } else if (this.form.goods_cat == "") {
        return this.$message({
          type: "error",
          message: "请选择商品分类",
        });
      }
      const res = await addGoods(this.form);
      if (res.data.meta.status == 201) {
        this.$message({
          type: "success",
          message: res.data.meta.msg,
        });
        this.form = {
          goods_name: "",
          goods_price: "0",
          goods_weight: "0",
          goods_number: "0",
          goods_introduce: "",
          goods_cat: "",
          pics: [],
          attrs: [],
        };
        this.$router.push("/goods");
      } else {
        this.$message({
          type: "error",
          message: res.data.meta.msg,
        });
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleChange(value) {
      this.value = value;
      this.form.goods_cat = value.join(",");
    },
    async getOptions() {
      const res = await getCategories();
      res.data.data.forEach((item) => {
        if (item.children) {
          this.options.push({
            value: item.cat_id,
            label: item.cat_name,
            children: item.children.map((item) => {
              if (item.children) {
                return {
                  value: item.cat_id,
                  label: item.cat_name,
                  children: item.children.map((item) => {
                    return {
                      value: item.cat_id,
                      label: item.cat_name,
                    };
                  }),
                };
              } else {
                return {
                  value: item.cat_id,
                  label: item.cat_name,
                };
              }
            }),
          });
        } else {
          this.options.push({
            value: item.cat_id,
            label: item.cat_name,
          });
        }
      });
      // console.log(this.options);
    },
    beforeTabLeave(activeName, oldActiveName) {
      this.$nextTick(() => {
        // console.log(this.$refs.ruleForm)
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            return false;
          }
        });
      });
      if (oldActiveName == "0" && activeName != "0") {
        if (this.form.goods_name == "") {
          this.$message({
            type: "error",
            message: "请填写商品名称",
          });
          return false;
        } else if (this.form.goods_price == "") {
          this.$message({
            type: "error",
            message: "请填写商品价格",
          });
          return false;
        } else if (this.form.goods_weight == "") {
          this.$message({
            type: "error",
            message: "请填写商品重量",
          });
          return false;
        } else if (this.form.goods_number == "") {
          this.$message({
            type: "error",
            message: "请填写商品数量",
          });
          return false;
        } else if (this.form.goods_cat == "") {
          this.$message({
            type: "error",
            message: "请选择商品分类",
          });
          return false;
        } else {
          this.active = parseInt(activeName);
          return true;
        }
      } else {
        this.active = parseInt(activeName);
      }
      if (oldActiveName == "2") {
        this.list2.forEach((item) => {
          this.form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          });
        });
        // if (this.form.attrs.length == this.list.length) {
        // this.list2.forEach((item, index) => {
        //   this.form.attrs[this.form.attrs.length + index] = {
        //     attr_id: item.attr_id,
        //     attr_value: item.attr_vals,
        //     };
        //   });
        // } else {
        //   this.list2.forEach((item, index) => {
        //     console.log(this.form.attrs[this.list.length + index])
        //     this.form.attrs[this.list.length + index].attr_value =
        //       item.attr_vals;
        //   });
        // }
      }
    },
  },
};
</script>
<style lang='less'  scoped>
main {
  width: 100%;
  background-color: #fff;
  margin-top: 15px;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 2px 2px 10px #ccc;
  .title {
    margin-bottom: 20px;
  }
  .red {
    color: red;
  }
  .green {
    color: #90ee90;
  }
}
.el-steps {
  margin: 20px 0 20px 100px;
}
</style>
